/**
 * Generate code from /{{projectName}}-core/src/main/java/{{packageName}}/core/{{modules}}/service/impl/Abstract{{entities@SQL}}Service.java.hbs
 */
package cn.ibizlab.core.open.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.util.*;
import cn.ibizlab.util.errors.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.open.domain.OpenAccessAuth;
import cn.ibizlab.core.open.filter.OpenAccessAuthSearchContext;
import cn.ibizlab.core.open.service.OpenAccessAuthService;
import cn.ibizlab.core.open.mapper.OpenAccessAuthMapper;
import cn.ibizlab.util.enums.Entities;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.ibizlab.core.open.domain.OpenAccess;
import cn.ibizlab.core.open.service.OpenAccessService;
import cn.ibizlab.core.ad.domain.SysPerson;
import cn.ibizlab.core.ad.service.SysPersonService;

/**
 * 实体[接入认证绑定] 服务对象接口实现
 *
 * @author generator
 */
@Slf4j
public abstract class AbstractOpenAccessAuthService extends ServiceImpl<OpenAccessAuthMapper,OpenAccessAuth> implements OpenAccessAuthService {

    @Autowired
    @Lazy
    protected OpenAccessService openAccessService;

    @Autowired
    @Lazy
    protected SysPersonService sysPersonService;

    protected int batchSize = 500;

    public OpenAccessAuth get(OpenAccessAuth et) {
        OpenAccessAuth rt = this.baseMapper.selectEntity(et);
        if(rt == null)
            throw new NotFoundException("数据不存在",Entities.OPEN_ACCESS_AUTH.toString(),et.getId());
        rt.copyTo(et,true);
        return et;
    }

    public List<OpenAccessAuth> getByEntities(List<OpenAccessAuth> entities) {
        entities.forEach(et->{
            if(ObjectUtils.isEmpty(et.getId()))
                et.setId((String)et.getDefaultKey(true));
            });
        return this.baseMapper.selectEntities(entities);
    }

    public void fillParentData(OpenAccessAuth et) {
        if(Entities.OPEN_ACCESS.equals(et.getContextParentEntity()) && et.getContextParentKey()!=null) {
            et.setAccessId((String)et.getContextParentKey());
            OpenAccess openAccess = et.getOpenAccess();
            if(openAccess == null) {
                openAccess = openAccessService.getById(et.getAccessId());
                et.setOpenAccess(openAccess);
            }
            if(!ObjectUtils.isEmpty(openAccess)) {
                et.setAccessId(openAccess.getId());
                et.setAccessType(openAccess.getOpenType());
                et.setAccessName(openAccess.getName());
            }
        }
        if(Entities.SYS_PERSON.equals(et.getContextParentEntity()) && et.getContextParentKey()!=null) {
            et.setPersonId((String)et.getContextParentKey());
        }
        if(!ObjectUtils.isEmpty(et.getPersonId())) {
            SysPerson sysPerson = et.getPerson();
            if(sysPerson == null) {
                sysPerson = sysPersonService.getById(et.getPersonId());
                et.setPerson(sysPerson);
            }
            if(!ObjectUtils.isEmpty(sysPerson)) {
                et.setPersonId(sysPerson.getId());
                et.setUid(sysPerson.getUid());
                et.setMobile(sysPerson.getMobile());
                et.setAvatar(sysPerson.getAvatar());
                et.setMail(sysPerson.getMail());
            }
        }
    }

    public OpenAccessAuth getDraft(OpenAccessAuth et) {
        fillParentData(et);
        return et;
    }

    public Integer checkKey(OpenAccessAuth et) {
        fillParentData(et);
        if(ObjectUtils.isEmpty(et.getId()))
            et.setId((String)et.getDefaultKey(true));
        return (!ObjectUtils.isEmpty(et.getId()) && this.count(Wrappers.<OpenAccessAuth>lambdaQuery().eq(OpenAccessAuth::getId, et.getId()))>0)?1:0;
    }

    @Override
    @Transactional
    public boolean create(OpenAccessAuth et) {
        fillParentData(et);
        if(ObjectUtils.isEmpty(et.getId()))
            et.setId((String)et.getDefaultKey(true));
        if(this.baseMapper.insert(et) < 1)
            return false;
        get(et);
        return true;
    }

    @Transactional
    public boolean createBatch(List<OpenAccessAuth> list) {
        list.forEach(this::fillParentData);
        list.forEach(et->{
            if(ObjectUtils.isEmpty(et.getId()))
                et.setId((String)et.getDefaultKey(true));
            });
        this.saveBatch(list, batchSize);
        return true;
    }

    @Transactional
    public boolean update(OpenAccessAuth et) {
        fillParentData(et);
        UpdateWrapper<OpenAccessAuth> qw = et.getUpdateWrapper(true);
        qw.eq("id", et.getId());
        if(!update(et, qw))
            return false;
        get(et);
        return true;
    }

    @Transactional
    public boolean updateBatch(List<OpenAccessAuth> list) {
        list.forEach(this::fillParentData);
        updateBatchById(list, batchSize);
        return true;
    }

    @Override
    @Transactional
    public boolean save(OpenAccessAuth et) {
        if(checkKey(et) > 0)
            return getSelf().update(et);
        else
            return getSelf().create(et);
    }

    @Transactional
    public boolean saveBatch(List<OpenAccessAuth> list) {
        if(ObjectUtils.isEmpty(list))
            return true;
        Map<String,OpenAccessAuth> before = getByEntities(list).stream().collect(Collectors.toMap(OpenAccessAuth::getId,e->e));
        List<OpenAccessAuth> create = new ArrayList<>();
        List<OpenAccessAuth> update = new ArrayList<>();
        list.forEach(sub->{
            if(ObjectUtils.isEmpty(sub.getId()))
                before.values().stream()
                        .filter(e->ObjectUtils.nullSafeEquals(sub.getDefaultKey(true),e.getDefaultKey(true)))
                        .findFirst().ifPresent(e->sub.setId(e.getId()));
            if(!ObjectUtils.isEmpty(sub.getId()) && before.containsKey(sub.getId()))
                update.add(sub);
            else
                create.add(sub);
        });
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else
            return true;
    }

    @Transactional
    public boolean remove(OpenAccessAuth et) {
        if(!remove(Wrappers.<OpenAccessAuth>lambdaQuery().eq(OpenAccessAuth::getId, et.getId())))
            return false;
        return true;
    }

    @Transactional
    public boolean removeByEntities(List<OpenAccessAuth> entities) {
        this.baseMapper.deleteEntities(entities);
        return true;
    }

    public Page<OpenAccessAuth> searchCompatible(OpenAccessAuthSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<OpenAccessAuth> pages=baseMapper.searchCompatible(context.getPages(),context,context.getSelectCond());
        List<OpenAccessAuth> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<OpenAccessAuth> listCompatible(OpenAccessAuthSearchContext context) {
        List<OpenAccessAuth> list = baseMapper.listCompatible(context,context.getSelectCond());
        return list;
    }

    public Page<OpenAccessAuth> searchDefault(OpenAccessAuthSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<OpenAccessAuth> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        List<OpenAccessAuth> list = pages.getRecords();
        return new PageImpl<>(list, context.getPageable(), pages.getTotal());
    }

    public List<OpenAccessAuth> listDefault(OpenAccessAuthSearchContext context) {
        List<OpenAccessAuth> list = baseMapper.listDefault(context,context.getSelectCond());
        return list;
    }

    public List<OpenAccessAuth> findByAccessId(List<String> accessIds) {
        List<OpenAccessAuth> list = baseMapper.findByAccessId(accessIds);
        return list;
    }

    public List<OpenAccessAuth> findByPersonId(List<String> personIds) {
        List<OpenAccessAuth> list = baseMapper.findByPersonId(personIds);
        return list;
    }

    public boolean removeByAccessId(String accessId) {
        return this.remove(Wrappers.<OpenAccessAuth>lambdaQuery().eq(OpenAccessAuth::getAccessId,accessId));
    }

    public boolean resetByAccessId(String accessId) {
        return this.update(Wrappers.<OpenAccessAuth>lambdaUpdate().eq(OpenAccessAuth::getAccessId,accessId));
    }

    public boolean saveByOpenAccess(OpenAccess openAccess,List<OpenAccessAuth> list) {
        if(list==null)
            return true;
        Map<String,OpenAccessAuth> before = findByAccessId(openAccess.getId()).stream().collect(Collectors.toMap(OpenAccessAuth::getId,e->e));
        List<OpenAccessAuth> update = new ArrayList<>();
        List<OpenAccessAuth> create = new ArrayList<>();

        for(OpenAccessAuth sub:list) {
            sub.setAccessId(openAccess.getId());
            sub.setOpenAccess(openAccess);
            if(ObjectUtils.isEmpty(sub.getId()))
                before.values().stream()
                        .filter(e->ObjectUtils.nullSafeEquals(sub.getDefaultKey(true),e.getDefaultKey(true)))
                        .findFirst().ifPresent(e->sub.setId(e.getId()));
            if(!ObjectUtils.isEmpty(sub.getId())&&before.containsKey(sub.getId())) {
                before.remove(sub.getId());
                update.add(sub);
            }
            else
                create.add(sub);
        }
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else if(!before.isEmpty() && !getSelf().removeBatch(before.keySet()))
            return false;
        else
            return true;
    }

    public boolean removeByPersonId(String personId) {
        return this.remove(Wrappers.<OpenAccessAuth>lambdaQuery().eq(OpenAccessAuth::getPersonId,personId));
    }

    public boolean resetByPersonId(String personId) {
        return this.update(Wrappers.<OpenAccessAuth>lambdaUpdate().eq(OpenAccessAuth::getPersonId,personId));
    }

    public boolean saveByPerson(SysPerson sysPerson,List<OpenAccessAuth> list) {
        if(list==null)
            return true;
        Map<String,OpenAccessAuth> before = findByPersonId(sysPerson.getId()).stream().collect(Collectors.toMap(OpenAccessAuth::getId,e->e));
        List<OpenAccessAuth> update = new ArrayList<>();
        List<OpenAccessAuth> create = new ArrayList<>();

        for(OpenAccessAuth sub:list) {
            sub.setPersonId(sysPerson.getId());
            sub.setPerson(sysPerson);
            if(ObjectUtils.isEmpty(sub.getId()))
                before.values().stream()
                        .filter(e->ObjectUtils.nullSafeEquals(sub.getDefaultKey(true),e.getDefaultKey(true)))
                        .findFirst().ifPresent(e->sub.setId(e.getId()));
            if(!ObjectUtils.isEmpty(sub.getId())&&before.containsKey(sub.getId())) {
                before.remove(sub.getId());
                update.add(sub);
            }
            else
                create.add(sub);
        }
        if(!update.isEmpty())
            update.forEach(item->this.getSelf().update(item));
        if(!create.isEmpty() && !getSelf().createBatch(create))
            return false;
        else if(!before.isEmpty() && !getSelf().removeBatch(before.keySet()))
            return false;
        else
            return true;
    }

    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.INSERT_ONE.getMethod())) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.UPDATE.getMethod())) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith(SqlMethod.DELETE.getMethod())) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    protected Class currentMapperClass() {
        return OpenAccessAuthMapper.class;
    }

    @Override
    protected Class currentModelClass() {
        return OpenAccessAuth.class;
    }
}